package handler

import (
	"encoding/json"
	"io"
	"log"
	"strconv"

	"github.com/lzppppppp/virapaksa-go/internal/system_monitor/middleware"
	"github.com/lzppppppp/virapaksa-go/internal/system_monitor/model"
	"github.com/spf13/viper"
)

// 输入对应数据中心，检查数据中心中个server集群压力，返回压力最小的编号
func CheckServerVolume(dc string) int {
	// 检查对应数据中心，那个集群压力小
	var minValue float64 = 100
	var minIndex int = 1
	for i := 1; i < viper.GetInt("server_num."+dc)+1; i++ {
		hostip_a := viper.GetString("server." + dc + ".prometheus-" + strconv.Itoa(i) + "-a")
		// 查看各集群内存容量
		url := model.FuncVar{
			IP:   viper.GetString("thanos.query"),
			Port: viper.GetString("component_port.query"),
			API:  "/api/v1/query?query=100-(node_memory_MemFree_bytes{hostip=\"" + hostip_a + "\"}%2Bnode_memory_Cached_bytes{hostip=\"" + hostip_a + "\"}%2Bnode_memory_Buffers_bytes{hostip=\"" + hostip_a + "\"})/node_memory_MemTotal_bytes{hostip=\"" + hostip_a + "\"}*100",
		}
		res := middleware.GetData(url)
		body, _ := io.ReadAll(res.Body)
		var data model.PromeQueryData
		// 解析http返回的json体
		if err := json.Unmarshal(body, &data); err == nil {
			if len(data.Data.Result) == 0 {
				log.Printf("INFO: %v memory info not found", hostip_a)
				// fmt.Println("memory info not found")
			} else {
				v := data.Data.Result[0].Value[1].(string)
				vF64, err := strconv.ParseFloat(v, 64)
				if err != nil {
					log.Printf("ERROR: string conver float64 failed")
					// fmt.Println("string conver float64 failed")
				}
				if minValue > vF64 {
					minValue = vF64
					minIndex = i
				}
			}
		}
	}
	return minIndex
}
